package com.samxfan;

import java.util.HashMap;
import java.util.Map;

/**
 * 购物车
 */
public class ShoppingCart {
    private Map<Fruit, Double> items; // 购物项
    private double discountThreshold; // 折扣阈值
    private double discountAmount; // 折扣金额

    /**
     * 构造方法
     */
    public ShoppingCart() {
        this.items = new HashMap<>();
        this.discountThreshold = 0;
        this.discountAmount = 0;
    }

    /**
     * 把指定重量的水果加入购物车
     * 
     * @param fruit  水果
     * @param weight 重量，单位是公斤
     */
    public void addItem(Fruit fruit, double weight) {
        if (weight < 0) {
            throw new IllegalArgumentException("重量不能为负！");
        }
        items.put(fruit, items.getOrDefault(fruit, 0.0) + weight);
    }

    /**
     *  设置满减促销: 满X元减Y元
     * 
     * @param x 满X元
     * @param y 减Y元
     */
    public void setSpendXSaveYPromotion(double x, double y) {
        this.discountThreshold = x;
        this.discountAmount = y;
    }

    /**
     *  计算购物车商品总价，包括折扣等
     * 
     * @return 商品总价
     */
    public double calculateTotal() {
        double total = 0;
        
        for (Map.Entry<Fruit, Double> entry : items.entrySet()) {
            Fruit fruit = entry.getKey();
            double weight = entry.getValue();
            total += fruit.calculatePrice(weight);
        }
        
        // 满X元减Y元
        if (discountThreshold > 0 && total >= discountThreshold) {
            int discountTimes = (int) (total / discountThreshold);
            total -= discountTimes * discountAmount;
        }
        
        return total;
    }
    
    /**
     * 获取购物车里的购物项
     * 
     * @return  购物项集合
     */
    public Map<Fruit, Double> getItems() {
        return new HashMap<>(items);
    }
}